// @algorithm @lc id=100293 lang=cpp
// @title shun-shi-zhen-da-yin-ju-zhen-lcof

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
    vector<int> direction{0, 1, 0, -1, 0};
    vector<int> spiralOrder(vector<vector<int>> &matrix) {
        int m = matrix.size();
        if (m == 0) {
            return {};
        }
        int n = matrix[0].size();
        if (n == 0) {
            return {};
        }
        vector<int> ans;
        vector<vector<bool>> visited(m, vector<bool>(n, false));
        int size = m * n;
        int flag = -1;
        int i = 0, j = 0;
        while (size) {
            if (flag == -1) {
                flag = 0;
                cout << "改变flag到0" << endl;
            }
            else if (flag == 3) {
                flag = 0;
                cout << "改变flag到0" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            else if (flag == 0) {
                flag = 1;
                cout << "改变flag到1" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            else if (flag == 1) {
                flag = 2;
                cout << "改变flag到2" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            else {
                flag = 3;
                cout << "改变flag到3" << endl;
                i += direction[flag];
                j += direction[flag + 1];
            }
            while (i >= 0 && i < m && j >= 0 && j < n && visited[i][j] == false) {
                visited[i][j] = true;
                cout << "i is " << i << ", "
                     << "j is " << j << "," << endl;
                cout << "输出" << matrix[i][j] << endl;
                ans.push_back(matrix[i][j]);
                --size;
                i += direction[flag];
                j += direction[flag + 1];
            }
            if (i == m) {
                i = m - 1;
            }
            else if (i == -1) {
                i = 0;
            }
            else if (j == n) {
                j = n - 1;
            }
            else if (j == -1) {
                j = 0;
            }
            else {
                i -= direction[flag];
                j -= direction[flag + 1];
            }
        }
        return ans;
    }
};